﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;

using BlogEngine.Core;

/// <summary>
/// 
/// </summary>
public partial class admin_Post : System.Web.UI.Page
{
	private Post _post;

	/// <summary>
	/// Handles the Load event of the Page control.
	/// </summary>
	/// <param name="sender">The source of the event.</param>
	/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
	protected void Page_Load(object sender, EventArgs e)
	{
		this.DataBind();
	}

	/// <summary>
	/// Binds a data source to the invoked server control and all its child controls.
	/// </summary>
	public override void DataBind()
	{
		// get post
		string qpostId = Request.QueryString["id"];
		int postId;

		if (Int32.TryParse(qpostId, out postId))
			_post = Post.GetPost(postId);
		else
			_post = new Post();

		if (!IsPostBack)
		{
			postTitle.Text = _post.Title;
			postContent.Text = _post.Content;
			postExcerpt.Text = _post.Excerpt;
			postTags.Text = GetTags(_post);
			postSlug.Text = _post.Slug;
			postStatusList.SelectedValue = _post.Status.ToString().ToLower();
			postAllowComments.Checked = _post.CommentStatus == PostCommentStatusType.Open;
			postAllowPingbacks.Checked = _post.PingStatus == PostPingStatusType.Open;

			// set date
			DateTime currentDate = _post.DatePublished.GetValueOrDefault(DateTime.Now);
			timestampMonth.SelectedValue = currentDate.Month.ToString();
			timestampDay.Text = currentDate.Day.ToString();
			timestampYear.Text = currentDate.Year.ToString();
			timestampHour.Text = currentDate.Hour.ToString();
			timestampMinute.Text = currentDate.Hour.ToString();

			// set category
			postCategory.DataSource = Term.Categories;
			postCategory.DataBind();
			postCategory.SelectedValue = _post.Categories.Count > 1 ? _post.Categories[0].Name : String.Empty;

			// set author
			postAuthor.DataSource = Membership.GetAllUsers();
			postAuthor.DataBind();
			postAuthor.SelectedValue = String.IsNullOrEmpty(_post.Author) ? Membership.GetUser().UserName : _post.Author;

			// set pinged
			pingbackList.DataSource = _post.Pinged;
		}
	}

	/// <summary>
	/// Gets the tags.
	/// </summary>
	/// <param name="post">The post.</param>
	/// <returns></returns>
	protected string GetTags(Post post)
	{
		IList<Term> tags = post.Tags;
		string[] array = new string[post.Tags.Count];

		for (int i = 0; i < array.Length; i++)
			array[i] = tags[i];

		return String.Join("; ", array);
	}

	/// <summary>
	/// Handles the Click event of the saveAndContinueButton control.
	/// </summary>
	/// <param name="sender">The source of the event.</param>
	/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
	protected void saveAndContinueButton_Click(object sender, EventArgs e)
	{
		SavePost((PostStatusType)Enum.Parse(typeof(PostStatusType), postStatusList.SelectedValue, true));
	}

	/// <summary>
	/// Handles the Click event of the saveButton control.
	/// </summary>
	/// <param name="sender">The source of the event.</param>
	/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
	protected void saveButton_Click(object sender, EventArgs e)
	{
		SavePost((PostStatusType)Enum.Parse(typeof(PostStatusType), postStatusList.SelectedValue, true));
	}

	/// <summary>
	/// Handles the Click event of the publishButton control.
	/// </summary>
	/// <param name="sender">The source of the event.</param>
	/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
	protected void publishButton_Click(object sender, EventArgs e)
	{
		SavePost(PostStatusType.Published);
	}

	/// <summary>
	/// Saves the post.
	/// </summary>
	/// <param name="status">The status.</param>
	private void SavePost(PostStatusType status)
	{
		_post.BeginEdit();

		_post.Title = postTitle.Text;
		_post.Content = postContent.Text;

		string[] tags = postTags.Text.Split(new char[] { ';', ',' });

		foreach (string tag in tags)
		{
			Term term = new Term(tag.Trim(), tag.Trim(), TermType.Tag);
			_post.Terms.Add(term);
		}

		_post.Terms.Add(new Term(postCategory.SelectedValue, postCategory.SelectedValue, TermType.Category));

		_post.Excerpt = postExcerpt.Text;
		_post.CommentStatus = postAllowComments.Checked ? PostCommentStatusType.Open : PostCommentStatusType.Closed;
		_post.PingStatus = postAllowPingbacks.Checked ? PostPingStatusType.Open : PostPingStatusType.Closed;
		_post.Slug = Utils.RemoveIllegalCharacters(String.IsNullOrEmpty(postSlug.Text.Trim()) ? _post.Title : postSlug.Text);
		_post.Status = status;

		if (status == PostStatusType.Published)
		{
			DateTime? postDate = null;
			int year, month, day, hour, minute;

			if (Int32.TryParse(timestampYear.Text, out year)
				&& Int32.TryParse(timestampMonth.SelectedValue, out month)
				&& Int32.TryParse(timestampDay.Text, out day)
				&& Int32.TryParse(timestampHour.Text, out hour)
				&& Int32.TryParse(timestampMinute.Text, out minute))
				postDate = new DateTime(year, month, day, hour, minute, 0);

			_post.DatePublished = postDate.GetValueOrDefault(DateTime.Now);
		}

		_post.Author = postAuthor.SelectedValue;
		_post.EndEdit();
	}
}
